from flask import Flask, request
import numpy as np
import open3d as o3d
from os.path import join
import os
import threading
from azure.recorder import AzureRcorder
from azure.reader import AzureReader
from azure.config import *

#############################################################################
# config_path = "D:\\Open3D-master\\config.json"
# output_path = "D:\\HHO\\20231001"
# file_name = "azure3"
# rosbag_url = "http://10.3.32.31:8000/"
# intrinsic_mat = np.array([
# 		911.25494384765625,
# 		0.0,
# 		0.0,
# 		0.0,
# 		910.99090576171875,
# 		0.0,
# 		963.2003173828125,
# 		544.46502685546875,
# 		1.0
# 	]).reshape((3,3)).T

# camera2world_dir = "D:\\Open3D-master\\extrinsic\\azure3\\20230928\\camera2world.txt"

# obj_dir = "D:\\Open3D-master\\obj"

############################################################################

stop_flag = threading.Event()
stop_flag.set()

name = None

recorder = None

app = Flask(__name__)

@app.route("/")
def hello():
    if not os.path.exists(output_path):
        os.makedirs(output_path)
    return "hello world"

@app.route("/vis", methods=["get"])
def vis():
    print(f"{request.args}")
    try:
        request.args["name"]
    except:
        return "name not found"
    _name = request.args["name"]
    convert_mkv = True
    if "convert_mkv" in request.args and request.args["convert_mkv"] == "0":
        convert_mkv = False
    VTS_add_time = 0
    if "VTS_add_time" in request.args:
        VTS_add_time = int(request.args["VTS_add_time"])*1000000
    cfg = {
        "vis_obj": False,
        "vis_person1": False,
        "vis_person2": False,
    }
    if "vis_obj" in request.args and request.args["vis_obj"] == "1":
        cfg["vis_obj"] = True
    if "vis_p1" in request.args and request.args["vis_p1"] == "1":
        cfg["vis_person1"] = True
    if "vis_p2" in request.args and request.args["vis_p2"] == "1":
        cfg["vis_person2"] = True
        
    if not os.path.exists(join(output_path, _name)):
        return "not found {}".format(_name)
    reader = AzureReader({
        "path":join(output_path, _name),
        "video_name": file_name,
        "output_dir": "vis",
        "segment_name" : _name,
        "rosbag_url" : rosbag_url + _name + "/VTS_data.npz",
        "intrinsic_mat" : intrinsic_mat,
        "camera2world_dir": camera2world_dir,
        "ts_dir" : join(output_path, _name, file_name+".txt"),
        "obj_dir" : obj_dir,
        "convert_mkv": convert_mkv,
        "VTS_add_time": VTS_add_time,
        "cfg":cfg
    })
    
    reader.start()
    
    return "ok"

@app.route("/start", methods=["get"])
def start():
    global name, stop_flag, recorder
    print(f"{request.args}")
    
    try:
        request.args["name"]
    except:
        return "name not found"
    name = request.args["name"]
    
    if not os.path.exists(join(output_path, name)):
        os.makedirs(join(output_path, name))
    
    if not stop_flag.is_set():
        return "is recording"
    
    stop_flag.clear()
    
    try:
        recorder = AzureRcorder({
            "config_path":config_path,
            "output_path":join(output_path, request.args["name"]),
            "file_name":file_name,
            }, stop_flag)
    except Exception as e:
        print(e)
        return f"error : {e}"
    
    recorder.start()    
        
    return file_name+ "  start: " + request.args["name"]

@app.route("/stop", methods=["get"])
def stop():
    global stop_flag, recorder, name
    if stop_flag.is_set():
        return "has been stopped"
    stop_flag.set()
    recorder.join()
    reader = o3d.io.AzureKinectMKVReader()
    reader.open(join(output_path, name, (file_name + ".mkv")))
    meta = reader.get_metadata()
    
    f = open(join(output_path, name, file_name + ".txt"), "r")
    ts = f.readlines()[0].split(",")
    
    recorder = None
    
    return file_name+ "  "+name +"  " +str((meta.stream_length_usec / 1000 /1000)) + "s  " + str(len(ts)) + "  " + str(len(ts) / (meta.stream_length_usec / 1000 /1000))
    
@app.route("/del", methods=["get"])
def delete():
    try:
        request.args["name"]
    except:
        return "name not found"
    name = request.args["name"]
    if not os.path.exists(join(output_path, name)):
        os.makedirs(join(output_path, name))
    with open(join(output_path, name, "deleted"), "w") as f:
        f.write("deleted")
    return "deleted"
    
    
if __name__ == "__main__":
    app.run("0.0.0.0", debug=True)